import * as echarts from 'echarts'
import { useEffect, useRef, useState } from 'react'
import useResizeObserver from './useResizeObserver'


/**
 * @description 图表hooks
 * @param chartRef 传递进来的 ref
 * @param chartInstance 返回出去的图表实例
 * @returns {[React.MutableRefObject<null>,unknown]}
 */
export const useCharts = () => {
  const chartRef = useRef(null)
  const [chartInstance, setChartInstance] = useState(null)
  const [loading, setLoading] = useState(false)
  const dimensions = useResizeObserver(chartRef)

  // 初始化
  useEffect(() => {
    if (!chartRef.current) return
    const chart = echarts.init(chartRef.current)

    setChartInstance(chart)

    return () => {
      chart.dispose() // 销毁图表
    }
  }, [])


  const handleChartResize = () => {
    chartInstance && chartInstance.resize({
      animation: {
        duration: 1500,
        easing: 'cubicInOut'
      }
    })
  }


  useEffect(() => {
    handleChartResize()
  }, [dimensions])


  return [
    chartRef,
    chartInstance,
    loading,
    setLoading
  ]

}
